package com.oktest.measure.ui.fragment

import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.cali.common.kt.*
import com.cali.libcore.base.BaseFragment
import com.cali.libcore.http.RetrofitManagement
import com.chad.library.adapter.base.BaseBinderAdapter
import com.oktest.measure.MyApp
import com.oktest.measure.R
import com.oktest.measure.entity.HomeNotice
import com.oktest.measure.entity.LineEntity
import com.oktest.measure.entity.TypeTitle
import com.oktest.measure.http.Api
import com.oktest.measure.item.home.*
import com.oktest.measure.kt.*
import com.oktest.measure.ui.fragment.home.HomeNoticeDetailFragment
import com.oktest.measure.ui.fragment.home.HomeTaskDetailFragment
import com.to.aboomy.banner.IndicatorView
import kotlinx.android.synthetic.main.fragment_main_home.*
import kotlinx.android.synthetic.main.item_home_banner.*
import kotlinx.android.synthetic.main.measure_loading_dialog.*
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileInputStream
import java.io.InputStream

/**
 * @Author hhh
 * @Date 2020/9/16
 */
class HomePageFragment : BaseFragment(){

    private var pageNum = 1

    private val homeAdapter by lazy {
        BaseBinderAdapter()
    }

    private val homeList = arrayListOf<Any>()

    override fun getLayoutId(): Int {
        return R.layout.fragment_main_home
    }

    override fun initData(savedInstanceState: Bundle?) {
        toolbarHelper?.apply {
            setTitleText("首页")
            setTitleTextColor(Color.WHITE)
        }
        getBanner()
        initRecyclerView()
        initRegister()
    }

    private fun initRegister() {
        registerEventSimple(EVENT_HOME_TASK_REFRESH){
            notifyAdapter()
        }
        registerEventSimple(EVENT_HOME_TASK_GET) {
            initNotice()
        }
    }

    private fun initRecyclerView() {
        homeAdapter.addItemBinder(HomeTitleBinder())
            .addItemBinder(HomeTaskBinder() {
                if (it.id.isEmpty()) {
                    toast("暂无任务")
                    return@HomeTaskBinder
                }
                startParentBrotherFragment(
                    HomeTaskDetailFragment()
                        .param(TASK_ID to it.id)
                )
            })
            .addItemBinder(HomeNoticeBinder(){
                if (it.id.isEmpty()) {
                    toast("暂无公告")
                    return@HomeNoticeBinder
                }
                startParentBrotherFragment(HomeNoticeDetailFragment()
                    .param(NOTICE_ID to it.id))
            })
            .addItemBinder(HomeLineBinder())

        homeRecyclerView.layoutManager = LinearLayoutManager(context)
        homeRecyclerView.adapter = homeAdapter

        // 下拉刷新
        refreshLayout.setOnRefreshListener {
            getBanner()
            initNotice()
            it.finishRefresh(true)
        }
        initNotice()
    }

    override fun hasToolbar(): Boolean {
        return true
    }

    override fun hasBackIcon(): Boolean {
        return false
    }

    companion object {
        fun newInstance(): HomePageFragment {
            return HomePageFragment()
        }
    }

    private fun notifyAdapter() {
        initNotice()
    }

    private fun initNotice() = launch{
        loadingDialog.tipTextView.text = "加载中.."
        loadingDialog.show()
        homeList.clear()
        homeList.add(TypeTitle("任务"))

        val homeTasks = MyApp.roomDatabase.homeTaskDao().loadAll()
        val taskItem = if (homeTasks.isEmpty() || homeTasks.last().id.isEmpty()) {
            resultTryContext {
                RetrofitManagement.instance.getService(Api::class.java)
                    .task().execute().body()?.data
            }.also {
                MyApp.roomDatabase.homeTaskDao().insert(it)
            }
        } else {
            homeTasks.last()
        }

        homeList.add(taskItem)
        homeList.add(LineEntity())
        homeList.add(TypeTitle("公告"))
        val noticeMap = hashMapOf<String,Int>()
        noticeMap["pageSize"] = 10
        noticeMap["pageNo"] = pageNum
        val noticeResult = resultListTryContext{
            RetrofitManagement.instance.getService(Api::class.java)
                .notice(noticeMap.jsonBody()).execute().body()?.data
        }
        MyApp.roomDatabase.homeNoticeDao().apply {
            insertList(noticeResult)
            val notices = loadAll()
            if (notices.isEmpty()) {
                // 默认提示
                homeList.add(HomeNotice())
            } else {
                homeList.addAll(notices)
            }
        }
        homeAdapter.setList(homeList)
        // 判空
        loadingDialog.dismiss()
    }
    // 轮播图
    private fun getBanner() = launch {
        val indicatorView = IndicatorView(context)
            .setIndicatorColor(Color.GRAY)
            .setIndicatorSelectorColor(Color.WHITE)

        val result = resultListTryContext {
            RetrofitManagement.instance.getService(Api::class.java)
                .banner().execute().body()?.data
        }
        val images = result.map {
            File(context?.filesDir, it.image)
        }
        // 初始化加载
        homeBanner.setIndicator(indicatorView)
            .setHolderCreator(ImageLoadingCreator())
            .setPages(images.map { it.absolutePath })

        val paths = arrayListOf<String>()

        images.forEach { file ->
            if(file.exists()){
                paths.add(file.absolutePath)
            } else {
                successTryContext{
                    val body = RetrofitManagement.instance.getService(Api::class.java)
                        .downloadBanner(file.name).execute().body()
                    body?.byteStream()?.apply {
                        file.writeInputStream(this)
                    }
                }
                paths.add(file.absolutePath)
            }
        }
        // 下载完毕
        homeBanner.setAutoPlay(true)
            .setIndicator(indicatorView)
            .setHolderCreator(ImageHolderCreator())
            .setPages(paths)
    }
}